package be.kuleuven.peno3.mobiletoledo.server;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Path ("/MenuHandler")
public class MenuServer {

	protected DatabaseManager manager = DatabaseManager.getInstance();

	@GET
	@Path ("/getMenu")
	@Produces ("application/json")
	public String getMenu(@QueryParam("dag") String dag, @QueryParam("restaurant") String restaurant){
		String query = "SELECT * FROM Menu";
	    query += " WHERE restaurant='"+restaurant+"' AND dag='"+dag+"'";
	    
		String result = queryForMessages(query);
		manager.disconnect();
		return result;
	}
	
	
	@SuppressWarnings("static-access")
	private String queryForMessages(String query) {
		JsonArray messages = new JsonArray();
		ResultSet rs = manager.query(query);
		Gson gson = new Gson();
		try {
			while(rs.next()) {
				JsonObject message = (JsonObject) gson.toJsonTree(manager.getColumnValues(rs));
				
				//get corresponding course from the database
//				int course_id = message.get("course_id").getAsInt();
//				query = "SELECT * FROM Courses WHERE id='" + course_id + "' limit 1";
//				message.add("course", querySimpleTable(query).get(0));

				messages.add(message);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		String asString = messages.toString();
		return asString;
	}
	
	
//	@SuppressWarnings({"static-access", "unchecked" })
//	private JsonArray querySimpleTable(String query) {
//		Vector course = new Vector();
//		ResultSet rs = manager.query(query);
//		Gson gson = new Gson();
//		try {
//			while(rs.next()) {
//				course.add(manager.getColumnValues(rs));
//			}
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//		return (JsonArray) gson.toJsonTree(course);
//	}

	
}
